import { defineStore } from 'pinia';
import { computed, reactive, nextTick } from 'vue';
import type {Position } from '@/views/data-manage/workflow/components/types';
import { NodeType } from '@/views/data-manage/workflow/components/types';
import { v4 as uuidv4 } from 'uuid';
// Store 类型定义
export type WorkflowStore = ReturnType<typeof useWorkflowStore>;

// 端口定义
export interface Port {
  id:string,
  name: string;
  code: string;
  type:string,
  value:string,
  click:string,
  fieldType:string,
}

// 节点数据定义
export interface NodeData {
  inputs: Port[];
  outputs: Port[];
}

// 添加组节点
export interface WorkflowGroup {
  id: string;
  title: string;
  position: Position;
  size: {
    width: number;
    height: number;
  };
  nodeIds: string[];  // 组内节点的ID列表
  containedGroups?: string[];  // 被该组包含的其他组的ID列表
}

// 节点
export interface WorkflowNode {
  id: string;
  title: string;
  type: string;
  position: Position;
  data: NodeData;
  showHead:string,
  size: {
    width: number;
    height: number;
  };
  color:string,
  icon:string
}

// 添加连接相关的类型定义
export interface Connection {
  id: string;
  sourcePortId: string;
  targetPortId: string;
  path: string;
  color:string;
}

export interface WorkflowState {
  nodes: WorkflowNode[];
  groups: WorkflowGroup[];
  selectedNodeId: string | null;
  selectedConnectionId: string | null;
  version: number;
  history: any[];
  historyIndex: number;
  tempData: Record<string, any>;
  connections: Connection[];
  selectedNodeIds: string[];
  selectedGroupId: string | null;
  selectedGroupIds: string[];
  selectedConnectionIds: string[];
  // 存储包含关系的 Map
  containments: Map<string, string[]>;
  // 添加菜单相关状态
  nodeMenu: {
    visible: boolean;
    position: {
      x: number;
      y: number;
    };
  };
  nodePortMenu: {
	id:string;
	node:WorkflowNode|null;
	port:Port | null;
    visible: boolean;
    position: {
      x: number;
      y: number;
    };
  };
}

// 添加框选区域类型
export interface SelectionArea {
  x1: number;
  y1: number;
  x2: number;
  y2: number;
}

// 对象类型枚举
export enum ObjectType {
  NODE = 'node',
  GROUP = 'group'
}

export const useWorkflowStore = defineStore('workflow', () => {
  // 状态管理
  const state = reactive<WorkflowState>({
    nodes: [],
    selectedNodeId: null,
    selectedConnectionId: null,
    version: 0,
    history: [],
    historyIndex: -1,
    tempData: {},
    connections: [],  // 初始化 connections 数组
    selectedNodeIds: [],  // 初始化 selectedNodeIds 数组
    groups: [],
    selectedGroupId: null,
    selectedGroupIds: [],  // 初始化为空数组
	selectedConnectionIds:[],
	containments: new Map(),
    // 初始化菜单状态
    nodeMenu: {
      visible: false,
      position: { x: 0, y: 0 },
    },
	nodePortMenu:{
		id:"",
		node:null,
		port:null,
		visible: false,
		position:{ x: 0, y: 0 },
	}
  });

  // Getters
  const getNodeById = computed(() => (id: string) => {
    return state.nodes.find(node => node.id === id);
  });

  const selectedNode = computed(() => {
    return state.selectedNodeId ? state.nodes.find(node => node.id === state.selectedNodeId) : null;
  });

  
  // 添加节点到菜单点击位置
  function initWorkflow(svgContainer:SVGSVGElement) {
    const svg = svgContainer;
    if (!svg) return;
    const transform = getSvgTransform(svg);
  	if (!transform) return;
  	nextTick(() => {
  	  if (svgContainer) {
  	    const rect = svgContainer.getBoundingClientRect();
  	    svgContainer.setAttribute('viewBox', `0 0 ${rect.width - 1} ${rect.height - 1}`);
  	    requestAnimationFrame(() => {
  	      svgContainer?.setAttribute('viewBox', `0 0 ${rect.width} ${rect.height}`);
  	    });
  	  }
  	});
  }

  function addNode(nodeType:NodeType, position: Position) {
    const newNode: WorkflowNode = {
		id: uuidv4(),
		type: nodeType.type,
		position: {
			x: position.x,
			y: position.y
		},
		data: { ... JSON.parse(nodeType.data) },
		title: nodeType.label,
		size: {
		  width: nodeType.width,
		  height: 50,
		},
		color: nodeType.color,
		icon: nodeType.icon,
		showHead: nodeType.showHead
	};
    state.nodes = [...state.nodes, newNode];
    state.version++; // 增加版本号触发更新
	state.selectedNodeId=newNode.id;
	updateContainments();
    return newNode;
  }

  function updateNodePosition(nodeId: string, position: Position) {
    const node = state.nodes.find(n => n.id === nodeId);
    if (node) {
      node.position = position;
      state.version++;
    }
  }


  function selectNode(nodeId: string | null, multiSelect = false) {
    // 如果不是多选模式，清除所有选中状态
    if (!multiSelect) {
      state.selectedConnectionIds = [];
	  state.selectedGroupIds=[];
	  state.selectedNodeIds = []; 
    }
    
    if (nodeId) {
      state.selectedNodeIds.push(nodeId);
    }
  //  state.version++;
  }

  function selectConnection(connectionId: string | null, multiSelect = false) {
    if (!multiSelect) {
      state.selectedConnectionIds = [];
	  state.selectedGroupIds=[];
	  state.selectedNodeIds = []; 
    }
    if (connectionId) {
      state.selectedConnectionIds.push(connectionId);
    }
  }

  /**
   * 框选选中元素设置
   * @param {string[]} nodeIds 
   * @param {string[]} groupIds 
   * @param {SelectionArea} selectionArea 
   */ 
  function boxSelectElementSettings(nodeIds: string[], groupIds: string[], selectionArea?: SelectionArea) {
    
    // 清除旧状态并设置新状态
    state.selectedNodeIds = nodeIds;
    state.selectedGroupIds = groupIds;
    
    // 更新选区信息
    if (selectionArea) {
      state.tempData.selectionArea = selectionArea;
    }
    
    incrementVersion();
  }

  function clearSelection() {
		state.selectedConnectionIds = [];
		state.selectedGroupIds=[];
		state.selectedNodeIds = []; 
		state.selectedGroupId=null;
		state.selectedNodeId=null;
		state.selectedConnectionId=null;
		if (state.tempData.selectionArea) {
			delete state.tempData.selectionArea;
		}
   // state.version++;
  }

  async function saveWorkflow() {
    try {
      const workflowData = {
        nodes: state.nodes,
        connections: state.connections
      };
      localStorage.setItem('workflow', JSON.stringify(workflowData));
    } catch (error) {
      console.error('Failed to save workflow:', error);
      throw error;
    }
  }

  function clearWorkflow() {
    state.nodes = [];
    state.connections = [];
    state.groups = [];
    state.containments = new Map();
    state.selectedNodeId = null;
    state.selectedConnectionId = null;
    state.selectedNodeIds = [];  // 清空选中节点
	state.selectedConnectionIds=[];
	state.selectedGroupIds=[];
    localStorage.removeItem('workflow');
  }

  function cleanup() {
    state.nodes = [];
    state.connections = [];
    state.selectedNodeId = null;
    state.selectedConnectionId = null;
	state.selectedGroupIds=[];
    state.selectedNodeIds = [];  // 清空选中节点
	state.selectedConnectionIds=[];
    state.version = 0;
    state.history = [];
    state.historyIndex = -1;
    state.tempData = {};
  }

  function incrementVersion() {
    state.version++;
  }

  function addConnection(connection: Connection) {
    state.connections.push(connection);
    state.version++;
  }
  
  function removeConnection(connectionId: string) {
    const index = state.connections.findIndex(c => c.id === connectionId);
    if (index !== -1) {
      state.connections.splice(index, 1);
      state.version++;
    }
  }
  
	function clearConnections() {
		state.connections = [];
		state.version++;
	}

	function updateConnection(updatedConnection: Connection) {
		const index = state.connections.findIndex(c => c.id === updatedConnection.id);
		if (index !== -1) {
		  state.connections[index] = updatedConnection;
		  state.version++; // 触发视图更新
		}
	}

	function batchUpdateConnections(connections: Connection[]) {
		connections.forEach(conn => {
		  const index = state.connections.findIndex(c => c.id === conn.id);
		  if (index !== -1) {
			state.connections[index] = conn;
		  }
		});
		state.version++;
	}

	// 修改 addGroup 函数
	function addGroup(title: string = 'Group Node') {
		const selectionArea = state.tempData.selectionArea as SelectionArea | undefined;
		if (!selectionArea) return;

		const padding = 20;
		const position: Position = {
		  x: selectionArea.x1 - padding,
		  y: selectionArea.y1 - padding
		};

		const groupSize: { width: number; height: number } = {
		  width: Math.abs(selectionArea.x2 - selectionArea.x1) + padding * 2,
		  height: Math.abs(selectionArea.y2 - selectionArea.y1) + padding * 2
		};

		// 检查是否在任何现有组内
		const isInsideExistingGroup = state.groups.some(group => {
		  return position.x >= group.position.x &&
				 position.x <= group.position.x + group.size.width &&
				 position.y >= group.position.y &&
				 position.y <= group.position.y + group.size.height;
		});

		const newGroup: WorkflowGroup = {
		  id: `group-${uuidv4()}`,
		  title,
		  position,
		  size: groupSize,
		  nodeIds: state.selectedNodeIds,
		  containedGroups: [],
		};

		// 如果在现有组内，添加到数组末尾（渲染在最上层）
		// 如果在组外，添加到数组开头（渲染在最下层）
		if (isInsideExistingGroup) {
		  state.groups.push(newGroup);
		} else {
		  state.groups.unshift(newGroup);
		}

		state.selectedNodeIds = [];
		state.selectedGroupIds = [newGroup.id];

		if (state.tempData.selectionArea) {
		  delete state.tempData.selectionArea;
		}
		state.version++;
		return newGroup;
	}

	function updateGroupPosition(groupId: string, position: Position) {
		const group = state.groups.find(g => g.id === groupId);
		if (group) {
		  group.position = position;
		  state.version++;
		}
	}

	function updateGroupSize(groupId: string, size: { width: number; height: number }) {
		const group = state.groups.find(g => g.id === groupId);
		if (group) {
		  group.size = size;
		  state.version++;
		}
	}

	function selectGroup(groupId: string | null, multiSelect = false) {
		// 如果不是多选模式，清除所有选中状态
		if (!multiSelect) {
		  state.selectedConnectionIds = [];
		  state.selectedGroupIds=[];
		  state.selectedNodeIds = []; 
		}
		if (groupId) {
		  if (multiSelect) {
			const index = state.selectedGroupIds.indexOf(groupId);
			if (index === -1) {
			  state.selectedGroupIds.push(groupId);
			} else {
			  state.selectedGroupIds.splice(index, 1);
			}
		  } else {
			state.selectedGroupIds = [groupId];
		  }
		}
		//state.version++;
	}

	// 检查对象包含关系
	function checkIntersections(groupId: string) {
		let currentRect: { x: number; y: number; width: number; height: number; };

		let currentGroupObject = state.groups.find(g => g.id === groupId);
		if (!currentGroupObject) return;
		currentRect = {
		  x: currentGroupObject.position.x,
		  y: currentGroupObject.position.y,
		  width: currentGroupObject.size.width,
		  height: currentGroupObject.size.height
		};

		let containments: string[]=[];
		let nodeIds: string[]=[];
		let containedGroups: string[]=[];
		

		// 检查与所有组的相交关系
		state.groups.forEach(group => {
			if (group.id === groupId) return;
			
			const groupRect = {
				x: group.position.x,
				y: group.position.y,
				width: group.size.width,
				height: group.size.height
			};
		  
			const isIntersecting = isRectIncludes(currentRect, groupRect);
			if(isIntersecting){
				containments.push(group.id);
				containedGroups.push(group.id);
			}
		});

		//组包含的节点
		state.nodes.forEach(node => {
			const nodeRect = {
			  x: node.position.x,
			  y: node.position.y,
			  width: node.size.width,
			  height: node.size.height
			};
			const isIntersecting = isRectIncludes(currentRect, nodeRect);
			if(isIntersecting){
				containments.push(node.id);
				nodeIds.push(node.id);
			}
		});
		
		currentGroupObject.nodeIds=nodeIds;
		currentGroupObject.containedGroups=containedGroups;
		state.containments.set(groupId, containments);
		state.version++;
	}
  
	function updateContainments(){
		state.groups.forEach(group => {
			checkIntersections(group.id)
		});
	}
  
	function  getBounds(elementById:string){
	  const groupElement = document.getElementById(elementById);
	  if (!groupElement) return undefined;
	  return groupElement.getBoundingClientRect();
	}
	
	function getSelectedNodes(x1:number,y1:number,x2:number,y2:number){
		// 确保矩形坐标和尺寸正确
		const [minX, maxX] = [Math.min(x1, x2), Math.max(x1, x2)];
		const [minY, maxY] = [Math.min(y1, y2), Math.max(y1, y2)];

		let currentRect = {
		  x: minX,
		  y: minY,
		  width: maxX - minX,
		  height: maxY - minY
		};
		
		let containments: string[]=[];
		
		//框选的节点
		state.nodes.forEach(node => {
			const nodeRect = {
			  x: node.position.x,
			  y: node.position.y,
			  width: node.size.width,
			  height: node.size.height
			};
			const isIntersecting = isRectIntersect(currentRect, nodeRect);
			if(isIntersecting){
				containments.push(node.id);
			}
		});
		
		return containments
	}
	
	function getSelectedGroups(x1:number,y1:number,x2:number,y2:number){
		// 确保矩形坐标和尺寸正确
		const [minX, maxX] = [Math.min(x1, x2), Math.max(x1, x2)];
		const [minY, maxY] = [Math.min(y1, y2), Math.max(y1, y2)];
	
		let currentRect = {
		  x: minX,
		  y: minY,
		  width: maxX - minX,
		  height: maxY - minY
		};
		
		let containments: string[]=[];
		
		//框选的组
		state.groups.forEach(group => {
			const groupRect = {
				x: group.position.x,
				y: group.position.y,
				width: group.size.width,
				height: group.size.height
			};
		  
			const isIntersecting = isRectIntersect(currentRect, groupRect);
			const isRectIncluded = isRectIncludes(groupRect,currentRect);
			if(isIntersecting && !isRectIncluded){
				containments.push(group.id);
			}
		});
		return containments;
	}
	
	function isRectIntersect(rect1: { x: number; y: number; width: number; height: number },
	                        rect2: { x: number; y: number; width: number; height: number }) {
	  return !(rect1.x + rect1.width < rect2.x ||
	           rect2.x + rect2.width < rect1.x ||
	           rect1.y + rect1.height < rect2.y ||
	           rect2.y + rect2.height < rect1.y);
	}
	
	/**
	 *  rect1 包含 rect2
	 * @param {{ x: number; y: number; width: number; height: number }} rect1 
	 * @param {{ x: number; y: number; width: number; height: number }} rect2 
	 * @return 
	 */ 
	function isRectIncludes(rect1: { x: number; y: number; width: number; height: number },
	                       rect2: { x: number; y: number; width: number; height: number }) {
	    return (
	        // 检查rect2的左边界是否在rect1的左边
	        rect2.x >= rect1.x &&
	        // 检查rect2的右边界是否在rect1的右边
	        (rect2.x + rect2.width) <= (rect1.x + rect1.width) &&
	        // 检查rect2的上边界是否在rect1的上边
	        rect2.y >= rect1.y &&
	        // 检查rect2的下边界是否在rect1的下边
	        (rect2.y + rect2.height) <= (rect1.y + rect1.height)
	    );
	}
	
	

	// 修改删除连接线的方法
	const removeConnectionsByPortId = (portId: string) => {
	  // 找到所有相关的连接
	  const relatedConnections = state.connections.filter(
	    conn => conn.sourcePortId === portId || conn.targetPortId === portId
	  );
	  // 删除连接并清理绑定关系
	  relatedConnections.forEach(conn => {
	    // 从连接数组中删除
	    const index = state.connections.findIndex(connection => connection.id === conn.id);
	    if (index > -1) {
	      state.connections.splice(index, 1);
	    }
	    
	    // 清理源节点的绑定关系
	    const sourceNode = state.nodes.find(node => 
	      node.data.outputs.some(out => `output-${node.id}-${out.id}-port` === conn.sourcePortId)
	    );
	    if (sourceNode) {
	      const output = sourceNode.data.outputs.find(out => 
	        `output-${sourceNode.id}-${out.id}-port` === conn.sourcePortId
	      );
	      if (output) {
	        output.value = '';  // 清除绑定值
	      }
	    }
	    
	    // 清理目标节点的绑定关系
	    const targetNode = state.nodes.find(node => 
	      node.data.inputs.some(inp => `input-${node.id}-${inp.id}-port` === conn.targetPortId)
	    );
	    if (targetNode) {
	      const input = targetNode.data.inputs.find(inp => 
	        `input-${targetNode.id}-${inp.id}-port` === conn.targetPortId
	      );
	      if (input) {
	        input.value = '';  // 清除绑定值
	      }
	    }
	  });
	  // 更新版本触发重渲染
	  incrementVersion();
	};
	
	const updatedConnections=(affectedConnections:any,svg:any)=>{
		return affectedConnections.value.map((conn: { sourcePortId: any; targetPortId: any; }) => {
		  // 使用更精确的端口选择器
		  const sourcePort = document.getElementById(`${conn.sourcePortId}-sign`);
		  const targetPort = document.getElementById(`${conn.targetPortId}-sign`);
			
		  if (sourcePort && targetPort) {
		    const sourceRect = sourcePort.getBoundingClientRect();
		    const targetRect = targetPort.getBoundingClientRect();
		    
		    const _data = getSvgTransform(svg);
			if(!_data) return conn;
		    const currentScale = _data.scale;
		    const currentTranslateX = _data.translateX;
		    const currentTranslateY = _data.translateY;
		    const currentSvgRect = svg.getBoundingClientRect();
		    
		    // 转换为 SVG 坐标
		    const sourcePoint = {
		      x: (sourceRect.left + sourceRect.width / 2 - currentSvgRect.left - currentTranslateX) / currentScale,
		      y: (sourceRect.top + sourceRect.height / 2 - currentSvgRect.top - currentTranslateY) / currentScale
		    };
		    
		    const targetPoint = {
		      x: (targetRect.left + targetRect.width / 2 - currentSvgRect.left - currentTranslateX) / currentScale,
		      y: (targetRect.top + targetRect.height / 2 - currentSvgRect.top - currentTranslateY) / currentScale
		    };
		    
		    // 计算控制点的偏移量
		    const dx = Math.abs(targetPoint.x - sourcePoint.x);
		    const controlOffset = Math.min(100, dx / 2);
		    
		    // 生成新的路径
		    const path = `M ${sourcePoint.x} ${sourcePoint.y} C ${sourcePoint.x + controlOffset} ${sourcePoint.y}, ${targetPoint.x - controlOffset} ${targetPoint.y}, ${targetPoint.x} ${targetPoint.y}`;
		    
		    return {
		      ...conn,
		      path
		    };
		  }
		  return conn;
		});
	}
	const updatedNodeConnections=(nodeConnections:Connection[],svg:SVGSVGElement)=>{
		// 使用 setTimeout 延迟更新，等待 DOM 更新完成
		setTimeout(() => {
			const updatedConnections = nodeConnections.map((conn:Connection) => {
				// 使用更精确的端口选择器
				const sourcePort = document.getElementById(`${conn.sourcePortId}-sign`);
				const targetPort = document.getElementById(`${conn.targetPortId}-sign`);
				
				if (sourcePort && targetPort) {
					const sourceRect = sourcePort.getBoundingClientRect();
					const targetRect = targetPort.getBoundingClientRect();
					
					const _data = getSvgTransform(svg);
					if(!_data){
						return conn;
					}
					const currentScale = _data.scale;
					const currentTranslateX = _data.translateX;
					const currentTranslateY = _data.translateY;
					const currentSvgRect = svg.getBoundingClientRect();
					
					// 转换为 SVG 坐标
					const sourcePoint = {
						x: (sourceRect.left + sourceRect.width / 2 - currentSvgRect.left - currentTranslateX) / currentScale,
						y: (sourceRect.top + sourceRect.height / 2 - currentSvgRect.top - currentTranslateY) / currentScale
					};
					
					const targetPoint = {
						x: (targetRect.left + targetRect.width / 2 - currentSvgRect.left - currentTranslateX) / currentScale,
						y: (targetRect.top + targetRect.height / 2 - currentSvgRect.top - currentTranslateY) / currentScale
					};
					
					// 计算控制点的偏移量
					const dx = Math.abs(targetPoint.x - sourcePoint.x);
					const controlOffset = Math.min(100, dx / 2);
					// 生成新的路径
					const path = `M ${sourcePoint.x} ${sourcePoint.y} C ${sourcePoint.x + controlOffset} ${sourcePoint.y}, ${targetPoint.x - controlOffset} ${targetPoint.y}, ${targetPoint.x} ${targetPoint.y}`;
					return {
						...conn,
						path
					};
				}
				return conn;
			});
			batchUpdateConnections(updatedConnections);
		}, 5); // 使用 0 延迟，让它在下一个事件循环中执行
	}
	
	const getSvgTransform = (svg: SVGSVGElement) => {
		if(!svg) return;
		
	  const contentGroup = svg.querySelector('.content-group');
	  const scaleGroup = contentGroup?.querySelector('g');
	  const transform = contentGroup?.getAttribute('transform') || '';
	  const scaleTransform = scaleGroup?.getAttribute('transform') || '';
	  
	  const translateMatch = transform.match(/translate\(([-\d.]+),([-\d.]+)\)/);
	  const scaleMatch = scaleTransform.match(/scale\(([\d.]+)\)/);
	  
	  return {
	    scale: scaleMatch ? parseFloat(scaleMatch[1]) : 1,
	    translateX: translateMatch ? parseFloat(translateMatch[1]) : 0,
	    translateY: translateMatch ? parseFloat(translateMatch[2]) : 0
	  };
	};

  // 显示节点菜单
  function showNodeMenu(event: MouseEvent) {
    const menuWidth = 384; // 假设菜单宽度为200
    const menuHeight = 400; // 假设菜单高度为300

    // 获取屏幕宽度和高度
    const screenWidth = window.innerWidth;
    const screenHeight = window.innerHeight;

    // 计算菜单的右下角位置
    const menuRight = event.clientX + menuWidth;
    const menuBottom = event.clientY + menuHeight;

    // 调整菜单位置
    let adjustedX = event.clientX;
    let adjustedY = event.clientY;

    // 如果菜单超出右边界，调整X位置
    if (menuRight > screenWidth) {
      adjustedX = event.clientX - menuWidth;
    }

    // 如果菜单超出下边界，调整Y位置
    if (menuBottom > screenHeight) {
      adjustedY =event.clientY - menuHeight ;
    }
	
	
	// if (menuBottom > screenHeight) {
	//   adjustedY = screenHeight - menuHeight;
	// }
	

    state.nodeMenu = {
      visible: true,
      position: {
        x: adjustedX,
        y: adjustedY,
      },
    };

    hideNodePortMenu();
  }

  // 隐藏节点菜单
  function hideNodeMenu() {
	  if(state.nodeMenu.visible==true){
		  state.nodeMenu.visible = false;
	  }
  }
  
  // 显示节点端口菜单
  function showNodePortMenu(id:string,node:WorkflowNode,port:Port,event: MouseEvent) {
	state.nodePortMenu = {
	  id:id,
	  node:node,
	  port:port,
      visible: true,
      position: {
        x: event.clientX,
        y: event.clientY
      },
    };
  }
  
  // 隐藏端口菜单
  function hideNodePortMenu() {
  	  if(state.nodePortMenu.visible==true){
  		  state.nodePortMenu.visible = false;
  	  }
  }

  // 添加节点到菜单点击位置
  function addNodeAtMenuPosition(nodeType: NodeType,svgContainer:SVGSVGElement) {
    // 获取菜单位置
    const menuPosition = state.nodeMenu.position;
    
    // 获取 SVG 容器和变换信息
    const svg = svgContainer;
    if (!svg) return;
    
    const transform = getSvgTransform(svg);
	if (!transform) return;
    const svgRect = svg.getBoundingClientRect();
    
    // 计算节点在画布中的位置
    const position = {
      x: (menuPosition.x - svgRect.left - transform.translateX) / transform.scale,
      y: (menuPosition.y - svgRect.top - transform.translateY) / transform.scale
    };
    
    const newNode = addNode(nodeType, position);
    
    // 隐藏菜单
    hideNodeMenu();
	
	nextTick(() => {
	  if (svgContainer) {
	    const rect = svgContainer.getBoundingClientRect();
	    svgContainer.setAttribute('viewBox', `0 0 ${rect.width - 1} ${rect.height - 1}`);
	    requestAnimationFrame(() => {
	      svgContainer?.setAttribute('viewBox', `0 0 ${rect.width} ${rect.height}`);
	    });
	  }
	});
    
    return newNode;
  }

	return {
		state,
		getNodeById,
		selectedNode,
		initWorkflow,
		addNode,
		updateNodePosition,
		selectNode,
		selectConnection,
		clearSelection,
		saveWorkflow,
		clearWorkflow,
		cleanup,
		incrementVersion,
		addConnection,
		removeConnection,
		updateConnection,
		clearConnections,
		batchUpdateConnections,
		boxSelectElementSettings,
		addGroup,
		updateGroupPosition,
		updateGroupSize,
		selectGroup,
		updateContainments,
		getSelectedNodes,
		getSelectedGroups,
		isRectIntersect,
		getBounds,
		removeConnectionsByPortId,
		getSvgTransform,
		updatedConnections,
		updatedNodeConnections,
		showNodeMenu,
		hideNodeMenu,
		showNodePortMenu,
		hideNodePortMenu,
		addNodeAtMenuPosition
	};
}); 